//
//  ViewController.m
//  下载小文件
//
//  Created by student on 16/3/31.
//  Copyright © 2016年 NIIT. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self downloadSmallFile2];
}

- (void)downloadSmallFile1
{
    for (int i=1;i<=16;i++)
    {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            //获取数据
            NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/MJServer/resources/images/minion_%02d.png",i];
            NSURL *url = [NSURL URLWithString:urlStr];
            NSData *data = [NSData dataWithContentsOfURL:url];
            //保存下来
            NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
            NSString *filePath = [path stringByAppendingPathComponent:url.lastPathComponent];//保存的路径
            NSLog(@"保存位置:%@",filePath);
            [data writeToFile:filePath atomically:YES];
        });
    }
}

- (void)downloadSmallFile2
{
    for(int i=1;i<=16;i++)
    {
        //获取数据
        NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/MJServer/resources/images/minion_%02d.png",i];
        NSURL *url = [NSURL URLWithString:urlStr];
        
        [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError)
        {
            //保存下来
            NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
            NSString *filePath = [path stringByAppendingPathComponent:url.lastPathComponent];//保存的路径
            NSLog(@"保存位置:%@",filePath);
            [data writeToFile:filePath atomically:YES];
        }];
    }
}





@end
